package com.contest.ws;


import com.contest.util.DateUtil;
import com.contest.util.RandomUtil;
import com.contest.util.WsNeed;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaoleilu.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.socket.*;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.*;

public class WsPushGamingData implements WebSocketHandler {
    private static Map<String, String> data = new HashMap<String, String>();
    private ObjectMapper json = new ObjectMapper();
    private static String user;
    private static Map<String, List<WebSocketSession>> sessions = Collections.synchronizedMap(new HashMap<String, List<WebSocketSession>>());

    Jedis redis = new Jedis("120.79.198.159", 6379);

    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        user = webSocketSession.getAttributes().get("flag").toString();
        redis.set(user, "1");

        List<WebSocketSession> session = sessions.get(user);
        if (session == null || session.size() == 0) {
            session = Collections.synchronizedList(new ArrayList<WebSocketSession>());
            session.add(webSocketSession);
        } else {
            session.add(webSocketSession);
        }
        sessions.put(user, session);
        webSocketSession.sendMessage(new TextMessage(JSONUtil.toJsonStr(data)));

    }

    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        Timer timer = new Timer();
        Map<String, String> temp = RandomUtil.hero();
        Set<String> keys = temp.keySet();
        for (String key : keys) {
            redis.hset("荒野行动", key, temp.get(key));
            redis.expire("荒野行动", DateUtil.getTodayTimeDifference());
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                String flg = redis.get(user);
                if (flg != null && flg.length() > 0 && "1".equals(flg)) {

                    try {
                        List<WebSocketSession> session = sessions.get(user);
                        if (session.size() > 0) {
                            for (WebSocketSession socketSession : session) {
                                if (socketSession.isOpen()) {
                                    socketSession.sendMessage(new TextMessage(json.writeValueAsString(temp)));
                                }
                            }
                        }
                        data.putAll(temp);
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                } else {
                    timer.cancel();
                }
            }
        }, 0, 3000);

    }

    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {

    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        String user =  webSocketSession.getAttributes().get("flag").toString();
        List<WebSocketSession> socketSessions = sessions.get(user);
        if(socketSessions != null && socketSessions.size() > 0) {
            socketSessions.remove(webSocketSession);
        }
        redis.del(user);
        System.out.println("连接关闭！");
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
